package com.lastproject.ejb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.AnswerDTO;
import com.lastproject.ejb.entities.Answer;
import com.lastproject.ejb.util.AnswerConversion;

/**
 * Session Bean implementation class AnswerDAO Author: Calin
 */
@Stateless
public class AnswerDAO implements AnswerDAORemote {

	/**
	 * Default constructor.
	 */
	@PersistenceContext
	EntityManager entityManager;

	@EJB
	AnswerConversion conversion;

	public AnswerDAO() {
		super();
	}

	@Override
	public void create(AnswerDTO answerDTO) {
		entityManager.persist(conversion.fromDTO(answerDTO));
	}

	@Override
	public void edit(AnswerDTO answerDTO) {
		// TODO Auto-generated method stub
		entityManager.merge(conversion.fromDTO(answerDTO));
	}

	@Override
	public void remove(AnswerDTO answerDTO) {
		// TODO Auto-generated method stub
		Answer answer = entityManager.find(Answer.class,
				conversion.fromDTO(answerDTO).getId());
		entityManager.remove(answer);
	}

	@Override
	public AnswerDTO findById(Object id) {
		Answer answer = entityManager.find(Answer.class, id);
		return conversion.fromEntity(answer);
	}

	@Override
	public List<AnswerDTO> getAll() {
		List<Answer> answers = entityManager.createQuery(
				"Select a from Answer a", Answer.class).getResultList();
		List<AnswerDTO> answersDTO = new ArrayList<AnswerDTO>();

		for (Answer answer : answers) {
			AnswerDTO aDTO = new AnswerDTO();
			aDTO = conversion.fromEntity(answer);
			answersDTO.add(aDTO);

		}

		return answersDTO;

	}

	@Override
	public List<AnswerDTO> getAnswersByQuestionOptionId(int questionOptionId) {
		List<Answer> answers = entityManager
				.createQuery(
						"Select a FROM Answer a JOIN a.questionOption qo WHERE qo.id =:id",
						Answer.class).setParameter("id", questionOptionId)
				.getResultList();
		List<AnswerDTO> answersDTO = new ArrayList<AnswerDTO>();

		for (Answer answer : answers) {
			AnswerDTO aDTO = new AnswerDTO();
			aDTO = conversion.fromEntity(answer);
			answersDTO.add(aDTO);

		}

		return answersDTO;
	}

}
